/**
 * ActionDecorator.java
 * @author: liuex
 * 2008-1-9 ����06:35:21
 *
 * note: 
 */
package org.lex.swing.prefs;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JPanel;

import org.lex.swing.ActionBuilder;


public class ActionDecorator extends CategoryDecorator {
	private static final ActionDecorator[] EMPTY = new ActionDecorator[0];
	private JPanel view = null;
	private JPanel actionsPane = null;
	private JButton[] actionButtons = null;

	public static <T extends Category> ActionDecorator[] decorate(T... categories) {
		if (null == categories || 0 == categories.length)
			return EMPTY;
		ActionDecorator[] tds = new ActionDecorator[categories.length];
		for (int i = 0; i < tds.length; i++)
			tds[i] = new ActionDecorator(categories[i]);
		return tds;
	}

	public ActionDecorator(final Category decoratee) {
		super(decoratee);
		this.initialize();
		// decoratee.addContentChangeListener( new ChangeListener(){
		// public void stateChanged( ChangeEvent e )
		// {}
		// } );
	}

	public Component getCategoryComponent() {
		return this.view;
	}

	private void initialize() {
		view = new JPanel(new BorderLayout());
		view.add(getDecoratee().getCategoryComponent(), BorderLayout.CENTER);
		view.add(getActionsPane(), BorderLayout.SOUTH);
	}

	private JPanel getActionsPane() {
		if (null == actionsPane) {
			FlowLayout flow = new FlowLayout(FlowLayout.TRAILING, 5, 5);
			flow.setAlignOnBaseline(true);
			actionsPane = new JPanel(flow);
			for (JButton b : this.getActionButtons())
				actionsPane.add(b);
		}
		return actionsPane;
	}

	private JButton[] getActionButtons() {
		if (null == this.actionButtons) {
			Category.Action[] actions = Category.Action.values();
			ArrayList<JButton> buttons = new ArrayList<JButton>(actions.length);
			for (Category.Action action : actions)
				if (this.getDecoratee().isSupported(action))
					buttons.add(this.createActionButton(action));
			this.actionButtons = buttons.toArray(new JButton[buttons.size()]);
		}
		return this.actionButtons;
	}

	private JButton createActionButton(final Category.Action action) {
		JButton button = new JButton();
		ActionBuilder ab = new ActionBuilder();
		ab.setName(action.getText());
		ab.setMnemonic(action.getMnemonic());
		ab.setActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				getDecoratee().performAction(action);
			}
		});
		button.setAction(ab);
		return button;
	}
}
